import 'dart:io';

import 'package:app_settings/app_settings.dart';
import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/gradient_button.dart';
import 'package:casdon/core/utils/wifi/wifi_status_monitor.dart';
import 'package:casdon/modules/device/ui/widgets/wifi_pwd_input_field.dart';
import 'package:casdon/modules/device/ui/widgets/wifi_selector_field.dart';
import 'package:casdon/auto_router.dart';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';

@RoutePage()
class WifiConfigScreen extends ConsumerStatefulWidget {
  final String pid;
  final String deviceName;
  final String? nextRoute;
  final String? virtualId;

  /// 标记是否以底部 present 形式展示
  final bool isModal;
  const WifiConfigScreen({
    super.key,
    required this.pid,
    required this.deviceName,
    required this.nextRoute,
    this.virtualId,
    this.isModal = false,
  });

  @override
  ConsumerState<WifiConfigScreen> createState() => _WifiConfigScreenState();
}

class _WifiConfigScreenState extends ConsumerState<WifiConfigScreen> {
  final TextEditingController _wifiPwdController = TextEditingController();
  String? _wifiPwd;
  String? _wifiSSId;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _ensureLocationPermission();
    });
  }

  Future<void> _ensureLocationPermission() async {
    if (!(Platform.isAndroid || Platform.isIOS)) {
      return;
    }

    final permission = Platform.isIOS
        ? Permission.locationWhenInUse
        : Permission.location;

    var status = await permission.status;
    if (status.isGranted || status.isLimited) {
      return;
    }

    await permission.request();
  }

  @override
  void dispose() {
    _wifiPwdController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final wifiToggleState = ref.watch(wifiStatusProvider);
    final content = SingleChildScrollView(
      padding: EdgeInsets.only(
        bottom: MediaQuery.of(context).viewInsets.bottom, // 考虑键盘高度
      ),
      child: Column(
        children: [
          wifiToggleState.when(
            data: (state) {
              if (state == true) {
                return _buildOnWifiWidget(context);
              } else {
                return _buildOffWifiWidget(context);
              }
            },
            loading: () => const SizedBox.shrink(),
            error: (err, _) => const SizedBox.shrink(),
          ),
        ],
      ),
    );

    if (widget.isModal) {
      return SafeArea(
        top: false,
        child: Material(
          color: Colors.transparent,
          child: Container(
            decoration: BoxDecoration(
              color: context.colorScheme.surface,
              borderRadius: const BorderRadius.vertical(
                top: Radius.circular(16),
              ),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const SizedBox(height: 8),
                Container(
                  width: 40,
                  height: 4,
                  decoration: BoxDecoration(
                    color: const Color(0xFFE0E0E0),
                    borderRadius: BorderRadius.circular(2),
                  ),
                ),
                content,
              ],
            ),
          ),
        ),
      );
    }

    return Scaffold(
      appBar: CommonAppBar(title: "添加设备"),
      body: content,
    );
  }

  Widget _buildOffWifiWidget(BuildContext context) {
    return Column(
      children: [
        SizedBox(height: 24.h),
        Text(
          "请开启手机WLAN功能",
          style: context.textTheme.labelLarge?.copyWith(
            color: context.customColorThemeNonNull.textColor1,
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          "连接2.4GHz WiFi以连接设备",
          style: context.textTheme.bodyMedium?.copyWith(
            color: context.customColorThemeNonNull.textColor3,
          ),
        ),
        SizedBox(height: 24.h),
        Image(image: AssetImage(Assets.images.wifiConfig.path)),

        SizedBox(height: 36.h),

        Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.w),
          child: GradientButton(
            text: "去开启WIFI",
            textStyle: context.textTheme.labelLarge?.copyWith(
              color: Colors.white,
            ),
            borderRadius: 24,
            onPressed: () => {
              AppSettings.openAppSettings(type: AppSettingsType.wifi),
            },
          ),
        ),
      ],
    );
  }

  Widget _buildOnWifiWidget(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min, // 重要：使用最小高度
      children: [
        SizedBox(height: 24.h),
        Text(
          "请选择 2.4GHz Wi-Fi 网络并输入密码",
          style: context.textTheme.labelLarge?.copyWith(
            color: context.customColorThemeNonNull.textColor1,
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          "如果你的 Wi-Fi 是 5GHz 的，请先设置为2.4GHz",
          style: context.textTheme.bodyMedium?.copyWith(
            color: context.customColorThemeNonNull.textColor3,
          ),
        ),
        SizedBox(height: 24.h),
        Image(image: AssetImage(Assets.images.wifiConfig.path)),

        SizedBox(height: 36.h),
        Padding(
          padding: EdgeInsets.only(left: 24.w, right: 24.h),
          child: WiFiSelectorField(
            onSelectedWifiChanged: (name) {
              _wifiSSId = name;
            },
            onTap: () {
              AppSettings.openAppSettings();
            },
            backgroundColor: const Color(0xFFF7F7F7),
            borderRadius: 12,
          ),
        ),
        SizedBox(height: 12),
        Padding(
          padding: EdgeInsets.only(left: 24.w, right: 24.h),
          child: WifiPwdInputField(
            controller: _wifiPwdController,
            onChanged: (value) {
              _wifiPwd = value;
            },
          ),
        ),
        SizedBox(height: 36.h),
        Padding(
          padding: EdgeInsets.only(
            left: 24.w,
            right: 24.w,
            bottom: MediaQuery.of(context).viewInsets.bottom + 20, // 键盘高度+额外空间
          ),
          child: GradientButton(
            text: "下一步",
            textStyle: context.textTheme.labelLarge?.copyWith(
              color: Colors.white,
            ),
            borderRadius: 24,
            onPressed: () => {_goNextPage(context)},
          ),
        ),
      ],
    );
  }

  void _goNextPage(BuildContext context) {
    if (widget.nextRoute == "add_device_progress") {
      _goAddDeviceProgressPage(context);
    } else if (widget.nextRoute == "pop") {
      context.router.maybePop({'ssid': _wifiSSId, 'pwd': _wifiPwd?.trim()});
    }
  }

  void _goAddDeviceProgressPage(BuildContext context) {
    if (_wifiSSId == null || _wifiPwd == null) {
      return;
    }

    if (_wifiSSId!.isEmpty || _wifiPwd!.trim().isEmpty) {
      return;
    }
    context.router.push(
      AddDeviceProgressRoute(
        pid: widget.pid,
        deviceName: widget.deviceName,
        ssid: _wifiSSId!,
        pwd: _wifiPwd!.trim(),
        virtualId: widget.virtualId,
      ),
    );
  }
}
